package com.gitee.wsl.compose.ui.richtext.edit.state

import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.unit.Density
import com.gitee.wsl.compose.ui.richtext.edit.model.paragraph.type.list.OrderedList

internal fun RichTextState.onTextLayout(
    textLayoutResult: TextLayoutResult,
    density: Density,
    maxLines: Int = Int.MAX_VALUE,
) {
    this.textLayoutResult = textLayoutResult
    adjustRichParagraphLayout(
        density = density,
        maxLines = maxLines,
    )
}

internal fun RichTextState.adjustRichParagraphLayout(
    density: Density,
    maxLines: Int,
) {
    var isParagraphUpdated = false

    richParagraphList.forEachIndexed { index, richParagraph ->
        val paragraphType = richParagraph.type
        if (index + 1 > maxLines || paragraphType !is OrderedList) return@forEachIndexed

        if (!paragraphType.startRichSpan.textRange.collapsed) {
            textLayoutResult?.let { textLayoutResult ->
                val start =
                    textLayoutResult.getHorizontalPosition(
                        offset = paragraphType.startRichSpan.textRange.min,
                        usePrimaryDirection = true
                    )
                val end =
                    textLayoutResult.getHorizontalPosition(
                        offset = paragraphType.startRichSpan.textRange.max,
                        usePrimaryDirection = true
                    )
                val distanceSp =
                    with(density) {
                        (end - start).toSp()
                    }

                if (paragraphType.startTextWidth != distanceSp) {
                    paragraphType.startTextWidth = distanceSp
                    isParagraphUpdated = true
                }
            }
        }
    }

    if (isParagraphUpdated)
        updateTextFieldValue(textFieldValue)
}
